import numpy as np

def loss(y, y_pred):
    return ((y_pred - y)**2).mean()
def gradient(x, y, w):
    return (2*w*x*x - 2*x*y).mean()
def forward(x):
    return w * x
# 定义数据集
X = np.array([1, 2, 3, 4], dtype=np.float32)
Y = np.array([2, 4, 6, 8], dtype=np.float32)
# 初始化学习率、迭代周期、w
lr = 0.01
n_iters = 20
w = 4
for epoch in range(n_iters):
    y_pred = forward(X)
    loss_value = loss(Y, y_pred)
    dw = gradient(X, Y, w)
    w -= lr * dw
    print(f'epoch {epoch+1}: w = {w:.3f}, loss = {loss_value:.8f}, dw = {dw:.3f}')